/* 线程池
*/
#include <iostream>
using std::cout;

#include <thread>
using std::thread;
#include <mutex>
using std::mutex; using std::unique_lock;

#include <condition_variable>
using std::condition_variable;

#include <string>
using std::string;
#include <queue>
using std::queue;
#include <vector>
using std::vector;

#include <functional>
using std::function;


/**
 * @brief 线程池
 */
class ThreadPool
{
private:
	vector<thread> threads;//线程数组
	queue<function<void()>> tasks;//任务队列
	mutex mtx;//互斥锁
	condition_variable condition;//条件变量
	bool stop;//线程是否终止
public:
	/**
	 * @brief 线程池构造函数
	 * @param numThreads 线程池中的线程数
	 */
	ThreadPool(int numThreads);
};

ThreadPool::ThreadPool(int numThreads) :stop(false)
{
	for (int i = 0; i < numThreads; i++)
	{
		threads.emplace_back([this]() {
			while (true)
			{
				unique_lock<mutex> lock(this->mtx);
				condition.wait(lock, [this]() {
					return !tasks.empty() || stop;
					});

				//线程终止
				if (stop) {
					return;
				}

				//取任务
				function<void()> task(std::move(tasks.front()));
				tasks.pop();
				lock.unlock();

				task();//执行任务
			}
		});
	}
}


int main(void)
{

}